﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServerManager.Network;
using System.Collections;
using System.Reflection;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using ServerManager.Classes;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace ServerManager
{
    public delegate void ReceivedServerList(IList list);

    public class ServerList
    {
        public event ReceivedServerList OnListReceived;

        private Int32 dataLength;
        private DrachamNetwork network;

        public ServerList(DrachamNetwork dn)
        {
            this.network = dn;
            this.network.NetworkHandler.AddHandler(MessageType.CXmlDataLength, this.DataLengthReceived);
        }

        public void DataLengthReceived()
        {
            this.dataLength = this.network.ReceiveInt32(6);
            this.network.NetworkHandler.AddHandler(MessageType.CXmlData, this.XmlDataReceived);
        }

        private void XmlDataReceived()
        {
            try
            {
                String xmlData = this.network.ReceiveString(this.dataLength);

                StringReader sr = new StringReader(xmlData);
                List<Character> list = (List<Character>)new XmlSerializer(typeof(List<Character>)).Deserialize(sr);

                this.OnListReceived(list);
            }
            catch (Exception e) 
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}
